﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace APMDemo
{
    class TaskCancelDemo
    {
        static void Main(string[] args)
        {
            Cancel();
            Console.ReadKey();
        }

        static void Cancel()
        {
            using (var tokenSource = new CancellationTokenSource())
            {
                // 获取一个CancellationToken实例对象
                CancellationToken token = tokenSource.Token;
                // 注册一个委托，在task取消之后调用
                token.Register(() => {
                    Console.WriteLine("Canceled ！");
                });

                // 启动一个task,并传入CancellationToken实例对象
                var task = Task.Run(() =>
                {
                    Console.WriteLine("开始执行任务了...");
                    Console.WriteLine("是否是池线程："+Thread.CurrentThread.IsThreadPoolThread);
                    for (var i = 0; i < 1000; i++)
                    {
                        Task.Delay(1000);
                        if (token.IsCancellationRequested)
                        {
                            Console.WriteLine("成功取消任务");
                        }
                    }
                }, token);

                var ts = Task.Factory.StartNew(() =>
                {
                    Console.WriteLine("Start running...");
                    Console.WriteLine("IsThreadPoolThread：" + Thread.CurrentThread.IsThreadPoolThread);
                    for (var i = 0; i < 1000; i++)
                    {
                        Thread.Sleep(1000);
                        if (token.IsCancellationRequested)
                        {
                            Console.WriteLine("Abort mission success!");
                            return;
                        }
                    }
                }, token);

                Console.WriteLine("Press enter to cancel task: ");
                Console.ReadKey();
                // 取消task
                tokenSource.Cancel();
                Console.ReadKey();
            }
        }
    }
}
